package com.tlgen.orm.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * 树形
 */
public class TreeUtils {

    /**
     * 获取树形数据
     * @param tList
     * @return
     * @param <T>
     */
    public static <T> List<T> tTree(List<T> tList) {
        JSONArray array = JSONArray.parseArray(JSONArray.toJSONString(tList)); // 源数据
        JSONArray tmpList = new JSONArray(); // 父节点数据
        JSONArray resList = new JSONArray(); // 最终返回结果数据
        // 获取父节点
        for (int i = 0; i < array.size(); i++) {
            String parentId = array.getJSONObject(i).getString("parentId");
            if (Objects.equals("0", parentId)) {
                JSONObject jsonObject = array.getJSONObject(i);
                tmpList.add(jsonObject);
            }
        }
        for (int i = 0; i < tmpList.size(); i++) {
            JSONObject jsonObject = tmpList.getJSONObject(i);
            JSONArray children = getChildren(jsonObject, array);
            if (!CollectionUtils.isEmpty(children)) {
                jsonObject.put("children", children);
            }
            resList.add(jsonObject);
        }
        return (List<T>) resList;
    }

    /**
     * 递归构造树形结构
     * @param jsonObject
     * @param jsonArray
     * @return
     */
    private static JSONArray getChildren(JSONObject jsonObject, JSONArray jsonArray) {
        JSONArray objects = new JSONArray();
        String id = jsonObject.getString("id");
        for (int i = 0; i < jsonArray.size(); i++) {
            String parentId = jsonArray.getJSONObject(i).getString("parentId");
            if (Objects.equals(id, parentId)) {
                JSONObject nextObj = jsonArray.getJSONObject(i);
                nextObj.put("children", getChildren(nextObj, jsonArray));
                objects.add(nextObj);
            }
        }
        return objects;
    }

}
